import React from 'react';
import { connect } from 'react-redux';
import { Form, Button, Input, InputNumber, Select, message } from 'antd';
import {
  messages, deepFullCopy
} from 'share/common';
import SwitchWrapper from 'components/template/widget/switch-wrapper/SwitchWrapper';
import './travel-share-style.scss';
import Chooser from 'components/chooser';
import deleteImg from 'images/expense/delete-amount.png';
const FormItem = Form.Item;
const Option = Select.Option;

class TravelShare extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      shareData: {
        isHidden: true,
        isSwitchOn: false,
        switchText: undefined,
        fieldOID: 'aaa'
      },
      shareList: [{
        userOid: props.userOID,
        name: props.userName,
        amount: 0
      },{
        userOid: null,
        name: null,
        amount: 0
      }]
    };
  };
  componentDidMount() {
    const { nowExpense, amount, feeAcknowledgers } = this.props;
    if (feeAcknowledgers && feeAcknowledgers.length > 1) {
      let shareData = this.state.shareData;
      shareData.isSwitchOn = true;
      this.props.onChangeSwitch(shareData.isSwitchOn);
      // console.log("amount", nowExpense)
      let trueAmount = Number(amount) || Number(nowExpense.amount);
      feeAcknowledgers.map((item, index) => {
        if (index > 0) {
          item.precent = item.amount / trueAmount;
        }
      });
      // console.log("feeAcknowledgers", feeAcknowledgers)
      this.setState({
        shareData,
        shareList: feeAcknowledgers
      })
    } else {
      let trueAmount = Number(amount) || Number(nowExpense.amount);
      this.props.onChange([{
        userOid: this.props.userOID,
        name: this.props.userName,
        amount: trueAmount
      }])
    }
  }
  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps", nextProps.amount, this.props.amount, nextProps)
    if (nextProps.amount && nextProps.nowExpense && (this.state.shareData.isSwitchOn || nextProps.readOnly)) {
      let shareList = this.state.shareList;
      console.log("1111111", shareList)
      if (shareList.length === 2) {
        if (shareList[1].precent) {
          shareList[1].amount = Number(nextProps.amount) * Number(shareList[1].precent);
          shareList[0].amount = nextProps.amount - shareList[1].amount;
        } else {
          shareList[0].amount = nextProps.amount;
          shareList[1].amount = 0;
        }
        this.setState({ shareList });
      } else {
        let num = Number(nextProps.amount);
        shareList.map((item, index) => {
          if (index > 0) {
            item.amount = Number(nextProps.amount) * Number(item.precent);
            num = num - Number(Number(nextProps.amount) * Number(item.precent));
          }
        });
        shareList[0].amount = Number(num);
        this.setState({ shareList });
      }
    }
    this.props.onChange(this.state.shareList)
  }
  // 共享人开关
  onSwitchChange = (value) => {
    let shareData = this.state.shareData;
    shareData.isSwitchOn = !shareData.isSwitchOn;
    this.props.onChangeSwitch(shareData.isSwitchOn);
    this.setState({ shareData, shareList: [{
      userOid: this.props.userOID,
      name: this.props.userName,
      amount: this.props.amount || this.props.nowExpense.amount
    },{
      userOid: null,
      name: null,
      amount: 0
    }] }, () => {
      if (shareData.isSwitchOn) {
        this.props.onChange(this.state.shareList)
      } else {
        this.props.onChange([]);
      }
    });
  };
  // 新增共享人
  addShareList = () => {
    let shareList = this.state.shareList;
    shareList.push({
      userOid: null,
      name: null,
      amount: 0,
      precent: 0
    });
    this.setState({ shareList });
    this.props.onChange(this.state.shareList)
  };
  // 金额修改
  changeShareAmount = (value, index) => {
    let shareList = this.state.shareList;
    let { amount } = this.props;
    // console.log("value", value, index)
    let num = 0;
    shareList.map((item, k) => {
      if (k !== index && k !== 0) {
        num += Number(item.amount)
      }
    })
    if ((Number(amount) - Number(num)) > value) {
      let needDeletAmount = 0;
      shareList.map((item, num) => {
        if (num !== 0 && num !== index) {
          needDeletAmount += item.amount
        }
      })
      shareList[index].amount = value;
      shareList[index].precent = value / amount;
      shareList[0].amount = amount - needDeletAmount - value;
      this.setState({ shareList })
      this.props.onChange(this.state.shareList)
    } else {
      message.warning('金额必须小于等于总金额');
    }
  };
  // 选择人员
  handleChangePerson = (value, index) => {
    // console.log("handleChangePerson", value, index)
    if (value && value[0]) {
      let shareList = this.state.shareList;
      shareList[index].userOid = value[0].userOID;
      shareList[index].name = value[0].fullName;
      this.setState({ shareList });
      this.props.onChange(this.state.shareList)
    }
  };
  // 删除共享人员
  deleteShare = (index) => {
    let shareList = this.state.shareList;
    shareList[0].amount = shareList[0].amount + shareList[index].amount;
    shareList.splice(index, 1);
    if (shareList.length === 1) {
      let shareData = this.state.shareData;
      shareData.isSwitchOn = false;
      this.setState({ shareList: [{
        userOid: this.props.userOID,
        name: this.props.userName,
        amount: 0
      },{
        userOid: null,
        name: null,
        amount: 0
      }], shareData});
      this.props.onChange([]);
      this.props.onChangeSwitch(shareData.isSwitchOn);
    } else {
      this.setState({ shareList });
      this.props.onChange(this.state.shareList)
    }
  };
  render() {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 }
    };
    const { shareData, shareList } = this.state;
    const { currencyCode, amount, currencyList, userName, readOnly } = this.props;
    console.log("currencyCode", shareList)
    let trueList = []
    if (readOnly) {
      shareList.map(item => {
        if (item.amount) {
          trueList.push(item)
        }
      })
    } else {
      trueList = shareList;
    }
    return (
      <div>
        <FormItem {...formItemLayout} label={messages("components.key1344")/*差旅餐饮/洗衣费共享*/}>
          {shareData && <SwitchWrapper
            isHidden={shareData.isHidden && !readOnly}
            isSwitchChecked={shareData.isSwitchOn}
            switchText={shareData.switchText}
            onSwitchChange={this.onSwitchChange}
            fieldInfo={shareData}
          >
            <div className="travel-share-box">
              {trueList && trueList.map((item, index) => (
                <div className="travel-share-list" key={index}>
                  <div className="input-user">
                    <Chooser
                      type={'user_all'}
                      value={item.userOid ? [{
                        userOID: item.userOid,
                        fullName: item.name
                      }] : []}
                      valueKey="userOID"
                      labelKey="fullName"
                      listExtraParams={{}}
                      single
                      showClear={false}
                      onChange={(value) => this.handleChangePerson(value, index)}
                      placeholder="请选择共享人"
                      disabled={index === 0 || readOnly}
                    />
                  </div>
                  <Select className="input-currery" placeholder="请选择币种" disabled value={currencyCode} showArrow={false}>
                    {currencyList.map(item => (
                      <Option key={item.currency}>
                        {item.currency}{this.props.language.code === 'zh_cn' ? ` ${item.currencyName}` : ''}
                      </Option>
                    ))}
                  </Select>
                  <InputNumber
                    className="input-amount"
                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\$\s?|(,*)/g, '')}
                    value={item.amount}
                    disabled={index === 0 || readOnly}
                    step={0.01}
                    precision={2}
                    onChange={(value) => this.changeShareAmount(value, index)}
                  />
                  {index > 0 && !readOnly && <img src={deleteImg} className="delete-image" onClick={() => this.deleteShare(index)} />}
                </div>
              ))}
              {!readOnly && <Button type="dashed" icon="plus" onClick={this.addShareList}>添加共享人</Button>}
            </div>
          </SwitchWrapper>}
        </FormItem>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    profile: state.login.profile,
    user: state.login.user,
    language: state.main.language,
  };
}
export default connect(mapStateToProps)(TravelShare);
